package com.skynet.supervision.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.time.LocalDateTime;

/**
 * 解决低版本shardingsphere无法处理jdk8新特性的handler
 */
@Component
@MappedTypes(LocalDateTime.class)
@MappedJdbcTypes(value = JdbcType.TIMESTAMP, includeNullJdbcType = true)
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, LocalDateTime localDateTime, JdbcType jdbcType) throws SQLException {
        preparedStatement.setObject(i, localDateTime);
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet resultSet, String s) throws SQLException {
        if (null == resultSet.getObject(s)) {
            return null;
        }
        return ((Timestamp)resultSet.getObject(s)).toLocalDateTime();
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet resultSet, int i) throws SQLException {
        if (null == resultSet.getObject(i)) {
            return null;
        }
        return ((Timestamp)resultSet.getObject(i)).toLocalDateTime();
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        if (null == callableStatement.getObject(i)) {
            return null;
        }
        return ((Timestamp)callableStatement.getObject(i)).toLocalDateTime();
    }
}
